# -*- coding: utf-8 -*-
# author : hxt
#   date : 2025/2/21
import copy
import allure


from apirun.extend.keywords import KeyWords
from apirun.core.globalContext import g_context
from apirun.utils.varrender import refresh
from apirun.utils.DynamicTitle import dynamic_title

'''
核心执行器
'''
class TestRunner:
    # 1、读取对应的数据
    # caseinfo = readYaml(r'D:\hxt\pywork\auto_api\apirun202504ddt\testcase\01_登录成功测试用例.yaml')
    # caseinfos = case_parser('yaml','./testcase')
    # caseinfos = case_parser('excel', './testcase')

    # 2、传参并执行
    # @pytest.mark.parametrize('caseinfo',caseinfo)
    # @pytest.mark.parametrize('caseinfo',caseinfos['case_infos'])
    def test_case_execute(self,caseinfo):
        print(f"-----【当前的测试用例：{caseinfo['_case_name']}】-----")
        # TODO 2-1:动态生成一下当前的测试用例标题
        # allure.dynamic.title(caseinfo['_case_name'])
        dynamic_title(caseinfo)

        # allure.dynamic.title(caseinfo['desc'])
        # TODO 2-2:基于步骤一步步执行
        try:
            keywords = KeyWords()
            local_context = caseinfo.get('context',{})
            # context = copy.deepcopy(g_context().show_dict())
            # context.update(local_context)

            steps = caseinfo.get('steps',None)
            for step in steps:
                step_name = list(step.keys())[0]
                step_value = list(step.values())[0]
                print(f'--开始执行步骤：{step_name} - {step_value}')

                # 每个步骤进行变量渲染
                context = copy.deepcopy(g_context().show_dict())
                context.update(local_context)
                step_value = eval(refresh(step_value,context))

                # 基于每个步骤的关键字，找到对应的方法，然后把参数给它
                # 通过【反射】的方式找到对应的方法
                with allure.step(step_name):
                    key = step_value.get('关键字')
                    try:
                        key_func = keywords.__getattribute__(key)
                    except AttributeError as e:
                        print('没有这个关键字方法',e)
                    key_func(**step_value)  #调用方法
        finally:
            print('----【当前用例步骤执行结束】----')


